<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class RegionCateController extends Controller
{
   /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 分类列表
        // SELECT c1.*, c2. NAME AS parentName, CONCAT(c1.path, ',', c1.id) AS sortPath  FROM regioncate AS c1 LEFT JOIN regioncate AS c2 ON c1.pid = c2.id ORDER BY sortPath
        $data = DB::table('regioncate AS c1')
            -> leftJoin('regioncate AS c2','c1.pid','=','c2.id')
            -> select('c1.*','c2.name AS parentName',DB::raw("CONCAT(c1.path,',',c1.id) AS sortPath"))
            -> where('c1.name','like',"%".$request -> input('search')."%")
            -> where('c1.pid',0)
            -> orderBy('sortPath')
            -> paginate($request -> input('num',50));
        $data1 = [];
        if($data[0])
        {
            foreach ($data as $key => $value) {
                $res=DB::table('regioncate AS c1')
                -> select('c1.*',DB::raw("CONCAT(c1.path,',',c1.id) AS sortPath"))
                -> where('c1.pid',$value -> id )
                -> orderBy('sortPath')
                -> get();
                if($res)
                {
                 $data1[$key] = $res;  
                }
            }
        }else
        {
            $data1 = [];
            $tmp1 = DB::table('regioncate AS c1')
            -> leftJoin('regioncate AS c2','c1.pid','=','c2.id')
            -> select('c1.*','c2.name AS parentName',DB::raw("CONCAT(c1.path,',',c1.id) AS sortPath"))
            -> where('c1.name','like',"%".$request -> input('search')."%")
            -> orderBy('sortPath')
            -> get();
            // dd($tmp1);
            foreach ($tmp1 as $key => $value) {
                $arr[]=DB::table('regioncate AS c1')
                -> select('c1.*',DB::raw("CONCAT(c1.path,',',c1.id) AS sortPath"))
                -> where('c1.id',$value -> pid )
                -> orderBy('sortPath')
                -> first()
                -> id;
                // dd($arr);
                if($arr)
                {
                 $data1[$key][] = $value;
                 // $data[$key] = $res[0];  
                }
            }
            // $c = count($arr);
            // $where = '';
            // foreach ($arr as $key => $value) {
            //     if($key == 0)
            //     {
            //         $where =  " c1.id = {$value} or c1.id = {$value}";
            //         // continue;
            //     }else
            //     {
            //        $where .=  " or c1.id = {$value} "; 
            //     }
                
            // }
            // dd($where);
            $data = DB::table('regioncate AS c1')
            -> leftJoin('regioncate AS c2','c1.pid','=','c2.id')
            -> select('c1.*','c2.name AS parentName',DB::raw("CONCAT(c1.path,',',c1.id) AS sortPath"))
            -> whereIn('c1.id',$arr)
            -> orderBy('sortPath')
            -> paginate($request -> input('num',50));
        // dd($data1);

        }
        // dd($data);
        // dd(empty($data[0]));

        // foreach ($data1[0] as $key => $value) {
        //     var_dump($value);
        // }
        // var_dump($data1);
// die;
// dd($data);
        // 分类的层级处理
        foreach ($data as $k => $v) {
            // 查找,的出现次数
           $num = substr_count($v -> path, ',');
           // 对查找出来的数量进行字符重复
           $data[$k] -> name = str_repeat('|---', $num).$v -> name;
           $data[$k] -> parentName = empty($v -> parentName)?'省/市/区':$v -> parentName;
        }
        // dd($request -> all());
        return view('admin.regioncate.index',['data' => $data,'request' => $request -> all(),'er' => $data1]);
        // dd($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // 显示表单
        // 分类添加表单
        // SELECT *,CONCAT(path,',',id) AS sortPath from regioncate ORDER BY sortPath
        // select('*',"CONCAT(path,',',id) AS sortPath") // 
        // 中的sql函数需要使用到DB::raw()方法,去当做原始表达式去解析
        $data = DB::table('regioncate')
             -> select('*',DB::raw("CONCAT(path,',',id) AS sortPath"))
             -> orderBy('sortPath')
             -> get();
        // dd($data);
        foreach ($data as $key => $value) {
            $num = substr_count($value -> path, ',');
            // var_dump($num);
            $data[$key] -> name = str_repeat('|---', $num).$value -> name;
        }
        // dd($data);


        return view('admin.regioncate.add',['data' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 获取表单传过来的数据
        // 执行分类添加
        // dd($request -> all());
        $data = $request -> except('_token');
        if($data['pid']=='0')
        {
            $data['path']= $data['pid'];
        }else
        { 
            $data['path']= DB::table('regioncate') -> where('id',$data['pid']) -> first() -> path . ','.$data['pid'];
        }
        // dd($data);  
        
        $res = DB::table('regioncate') -> insert($data);
        if($res)
        {
            return redirect('/admin/regioncate') -> with(['info' => '分类添加成功']);
        }else
        {
            return back() -> with(['info' => '分类添加失败']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 编辑分类
        
        // dd($id);
        $data = DB::table('regioncate') -> where('id',$id) -> first();
        // dd($data);
        // 查询所有的父分类
        $allData = DB::table('regioncate')
            -> select('*',DB::raw("CONCAT(path,',',id) AS sortPath"))
            -> orderBy('sortPath')
            -> get();
        foreach ($allData as $k => $v) {
           $num = substr_count($v -> path,',');
           $allData[$k] -> name = str_repeat('|---',$num).$v -> name;
        }
        // dd($allData);
        return view('admin.regioncate.edit',['data' => $data,'allData' => $allData]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        // dd($request);
        $data = $request -> except('_token','_method');

        if($data['pid']=='0')
        {
            $data['path']= $data['pid'];
        }else
        {
            $data['path']= DB::table('regioncate') -> where('id',$data['pid']) -> first() -> path . ','.$data['pid'];
            // $data['path']= DB::table('regioncate') -> where('id',$data['pid']) -> first() -> path . ','.$data['pid'];
        }
        
        // dd($data);
        $res = DB::table('regioncate') -> where('id',$id) -> update($data);
        if($res)
        {
            return redirect('/admin/regioncate') -> with(['info' => '分类修改成功']);
        }else
        {
            return back() -> with(['info' => '分类修改失败']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        // dd($id);
        $r = DB::table('regioncate') -> where('pid',$id) -> first();
        if($r)
        {
            return back() -> with(['info' => '此类下有子分类,不允许删除']);
        }
        $res = DB::table('regioncate') -> delete($id);
        if($res)
        {
            return redirect('/admin/regioncate') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }
    public function ajaxName(Request $request)
    {
        // return 111;
        // dd($request -> all());
        $id = $request -> input('id');
        // $data = DB::table('regioncate') -> select('status') -> where('id',$id) -> first();
        // dd($data);
        // if($data -> status == 0)
        // {
            $res = DB::table('regioncate') -> where('id',$id) -> update($request->all());
            if($res)
            {
              return response() -> json(1);  
            }else
            {
              // 4 表示修改失败
              return response() -> json(0);
            }
            
        // }else
        // {
            // $res = DB::table('users') -> where('id',$id) -> update(['status' => 0]);
            // if($res)
            // {
            //   return response() -> json(0);  
            // }else
            // {
            //   // 4 表示修改失败
            //   return response() -> json(4);
            // }
        // }
        // return $id;
    }
}
